package com.itlaobing.exam.service;

import com.itlaobing.exam.entity.User;
import com.itlaobing.exam.foundation.support.EncryptHelper;
import com.itlaobing.exam.foundation.support.EncryptType;
import com.itlaobing.exam.foundation.support.StringHelper;
import com.itlaobing.exam.mapper.UserMapper;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.time.LocalDate;

public class UserService {

    private static final Logger logger = LogManager.getLogger( UserService.class );

    private UserMapper userMapper;

    public boolean saveUser( User user ) {
        logger.info("保存用户");

        final String salt = StringHelper.random(10);
        user.setSalt(salt);// 为user对象设置盐值

        final String password = user.getPassword();// 获得用户指定的原始密码

        String encrypted = this.encrypt(password,salt);// 调用加密方法对原始密码加盐加密

        user.setPassword(encrypted);//将加盐且加密后的字符串设置到user对象中
        
        user.setJoinDate(LocalDate.now());// 设置 加入日期

        int count = userMapper.save(user);
        return  count > 0;
    }
    /**
     * 对原始密码加盐、加密
     * @param password 原始密码
     * @param salt 盐值
     * @return 返回加密后的字符串
     */
    private String encrypt(String password, String salt) {
        //通过截取 salt 随机生成的盐值将 password 放在中间形成 新的密码值
        String passwordWithSalt = salt.substring(0,5) + password + salt.substring(5);
        //将新的密码值
        String encrypted = EncryptHelper.encrypt(passwordWithSalt, EncryptType.SHA1);
        return encrypted;
    }

    public User findUser( String username ) {
        logger.info( "根据用户名获取用户" );
        return userMapper.find( username );
    }

    public boolean editUser( User user ) {
        logger.info( "修改用户个人信息" );
        int count = userMapper.update( user );
        return count > 0 ;
    }

    public boolean deleteUser( Integer id  ) {
        logger.info( "删除用户" );
        int count = userMapper.delete( id );
        return count > 0 ;
    }

    public UserMapper getUserMapper() {
        return userMapper;
    }

    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
}
